package cn.itcast.utils;


import cn.itcast.pojo.AliProperties;
import com.aliyun.oss.*;
import com.aliyun.oss.common.auth.CredentialsProviderFactory;
import com.aliyun.oss.common.auth.EnvironmentVariableCredentialsProvider;
import com.aliyun.oss.common.comm.SignVersion;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

@Slf4j
public class OSSUtils {
    /*
        如何注入配置文件中的数据
        第一种方案:
            @Value("${键}) 如何检测是否配置正确, 按住ctrl键变小手, 点击能够调到配置中算成功
            缺点:
                (1)一次只能注入一个,有大量数据需要注入的话比较麻烦!!!
                (2)不能注入特殊类型, 只能注入简单类型
        第二种方案:
            ConfigurationProperties(prefix="前缀")
            可以解决大量数据的注入
            步骤:
                (1) 定义一个实体类, 其中成员变量的名字和配置文件中最后一级匹配
                (2) 通过ConfigurationProperties(prefix="前缀")设置前缀,会自动将前缀中的对应属性注入
            优点:
                可以注入各种数据类型
     */
   /* @Value("${ali.oss.endpoint}")
    private String endpoint;
    @Value("${ali.oss.bucketName}")
    private String bucketName;
    @Value("${ali.oss.region}")
    private String region;*/
    //@Autowired
    private AliProperties aliProperties;

    public String upload(MultipartFile file) throws com.aliyuncs.exceptions.ClientException {
        log.warn("读取的配置文件中的内容是{}"+aliProperties);
        /*// Endpoint以华东1（杭州）为例，填写为https://oss-cn-hangzhou.aliyuncs.com，其它Region请按实际情况填写。
        String endpoint = "https://oss-cn-beijing.aliyuncs.com";
        String bucketName = "junjian12345";
        // 填写Bucket所在地域。以华东1（杭州）为例，Region填写为cn-hangzhou。
        String region = "cn-beijing";*/

        // 从环境变量中获取访问凭证。运行本代码示例之前，请先配置环境变量,需要重启一下idea环境变量才能生效
        EnvironmentVariableCredentialsProvider credentialsProvider =
                CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();

        // 创建OSSClient实例。
        // 当OSSClient实例不再使用时，调用shutdown方法以释放资源。
        ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
        // 显式声明使用 V4 签名算法
        clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);
        OSS ossClient = OSSClientBuilder.create()
                .endpoint(aliProperties.getEndpoint())
                .credentialsProvider(credentialsProvider)
                .region(aliProperties.getRegion())
                .build();
        try {
            // 1. 创建存储空间（Bucket）
            // ossClient.createBucket(bucketName);

            // 2. 上传文件
            //String objectName = "d:/b.jpeg";
            String originalFilename = file.getOriginalFilename();
            ossClient.putObject(aliProperties.getBucketName(), originalFilename, file.getInputStream());
            System.out.println("2. 文件 " + originalFilename + " 上传成功。");

            //https://junjian12345.oss-cn-beijing.aliyuncs.com/b.jpeg?
            return "https://" + aliProperties.getBucketName() + "." + aliProperties.getEndpoint().substring(aliProperties.getEndpoint().lastIndexOf("/") + 1) + "/" + originalFilename;
            // 3. 下载文件
           /* OSSObject ossObject = ossClient.getObject(bucketName, objectName);
            InputStream contentStream = ossObject.getObjectContent();
            BufferedReader reader = new BufferedReader(new InputStreamReader(contentStream));
            String line;
            System.out.println("3. 下载的文件内容：");
            while ((line = reader.readLine()) != null) {
                System.out.println(line);
            }
            contentStream.close();
            // 4. 列出文件
            System.out.println("4. 列出 Bucket 中的文件：");
            ObjectListing objectListing = ossClient.listObjects(bucketName);
            for (OSSObjectSummary objectSummary : objectListing.getObjectSummaries()) {
                System.out.println(" - " + objectSummary.getKey() + " (大小 = " + objectSummary.getSize() + ")");
            }
            // 5. 删除文件
            ossClient.deleteObject(bucketName, objectName);
            System.out.println("5. 文件 " + objectName + " 删除成功。");
            // 6. 删除存储空间（Bucket）
            ossClient.deleteBucket(bucketName);
            System.out.println("6. Bucket " + bucketName + " 删除成功。");*/
        } catch (OSSException oe) {
            System.out.println("Caught an OSSException, which means your request made it to OSS, "
                    + "but was rejected with an error response for some reason.");
            System.out.println("Error Message:" + oe.getErrorMessage());
            System.out.println("Error Code:" + oe.getErrorCode());
            System.out.println("Request ID:" + oe.getRequestId());
            System.out.println("Host ID:" + oe.getHostId());
        } catch (ClientException | IOException ce) {
            System.out.println("Caught an ClientException, which means the client encountered "
                    + "a serious internal problem while trying to communicate with OSS, "
                    + "such as not being able to access the network.");
            System.out.println("Error Message:" + ce.getMessage());
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
        return null;
    }
    public String upload(File file) throws com.aliyuncs.exceptions.ClientException {
        log.warn("读取的配置文件中的内容是{}"+aliProperties);
        /*// Endpoint以华东1（杭州）为例，填写为https://oss-cn-hangzhou.aliyuncs.com，其它Region请按实际情况填写。
        String endpoint = "https://oss-cn-beijing.aliyuncs.com";
        String bucketName = "junjian12345";
        // 填写Bucket所在地域。以华东1（杭州）为例，Region填写为cn-hangzhou。
        String region = "cn-beijing";*/

        // 从环境变量中获取访问凭证。运行本代码示例之前，请先配置环境变量,需要重启一下idea环境变量才能生效
        EnvironmentVariableCredentialsProvider credentialsProvider =
                CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();

        // 创建OSSClient实例。
        // 当OSSClient实例不再使用时，调用shutdown方法以释放资源。
        ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
        // 显式声明使用 V4 签名算法
        clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);
        OSS ossClient = OSSClientBuilder.create()
                .endpoint(aliProperties.getEndpoint())
                .credentialsProvider(credentialsProvider)
                .region(aliProperties.getRegion())
                .build();
        try {
            // 1. 创建存储空间（Bucket）
            // ossClient.createBucket(bucketName);

            // 2. 上传文件
            //String objectName = "d:/b.jpeg";
            ossClient.putObject(aliProperties.getBucketName(), "a.png", new FileInputStream(file));
            System.out.println("2. 文件 " + "a.png" + " 上传成功。");

            //https://junjian12345.oss-cn-beijing.aliyuncs.com/b.jpeg?
            return "https://" + aliProperties.getBucketName() + "." + aliProperties.getEndpoint().substring(aliProperties.getEndpoint().lastIndexOf("/") + 1) + "/" + "a.png";
            // 3. 下载文件
           /* OSSObject ossObject = ossClient.getObject(bucketName, objectName);
            InputStream contentStream = ossObject.getObjectContent();
            BufferedReader reader = new BufferedReader(new InputStreamReader(contentStream));
            String line;
            System.out.println("3. 下载的文件内容：");
            while ((line = reader.readLine()) != null) {
                System.out.println(line);
            }
            contentStream.close();
            // 4. 列出文件
            System.out.println("4. 列出 Bucket 中的文件：");
            ObjectListing objectListing = ossClient.listObjects(bucketName);
            for (OSSObjectSummary objectSummary : objectListing.getObjectSummaries()) {
                System.out.println(" - " + objectSummary.getKey() + " (大小 = " + objectSummary.getSize() + ")");
            }
            // 5. 删除文件
            ossClient.deleteObject(bucketName, objectName);
            System.out.println("5. 文件 " + objectName + " 删除成功。");
            // 6. 删除存储空间（Bucket）
            ossClient.deleteBucket(bucketName);
            System.out.println("6. Bucket " + bucketName + " 删除成功。");*/
        } catch (OSSException oe) {
            System.out.println("Caught an OSSException, which means your request made it to OSS, "
                    + "but was rejected with an error response for some reason.");
            System.out.println("Error Message:" + oe.getErrorMessage());
            System.out.println("Error Code:" + oe.getErrorCode());
            System.out.println("Request ID:" + oe.getRequestId());
            System.out.println("Host ID:" + oe.getHostId());
        } catch (ClientException | IOException ce) {
            System.out.println("Caught an ClientException, which means the client encountered "
                    + "a serious internal problem while trying to communicate with OSS, "
                    + "such as not being able to access the network.");
            System.out.println("Error Message:" + ce.getMessage());
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
        return null;
    }
}
